<?php

class get
{
    public static function index():bool
    {
        loadHtml("index",false,[],false);
        return true;
    }

    public static function main():bool
    {
        $a = session_get("role")=="teacher" ?'<input type="button" value="清空" id="clear">':'';
        if (args_get("role")=="teacher"){
            session_set("role","teacher");
            header("Location: /main");
        }
        loadHtml("main",false,["CLEAR"=>$a]);
        return true;
    }

    public static function img():bool
    {
        if(session_get("skip-sleep")!="yes"){
            // usleep(USLEEP_TIME);
        }
        $tag = args_get("tag");
        $fn = "upload/$tag.jpg";
        $fn_gif = "upload/$tag.gif";
        if (empty($tag)){
            readfile(linkProcess("{IMG_blank_jpg}"));
            header('Content-Type:image/jpeg;charset=utf-8');
        }else {
            if (!empty(file_get_contents($fn_gif))) {
                readfile($fn_gif);
                header('Content-Type:image/gif;charset=utf-8');
            } elseif (!empty(file_get_contents($fn))) {
                readfile($fn);
                header('Content-Type:image/jpeg;charset=utf-8');
            } else {
                readfile(linkProcess("{IMG_blank_jpg}"));
                header('Content-Type:image/jpeg;charset=utf-8');
            }
        }

//        readfile($fn);
        return true;
    }

    public static function vote():bool
    {
        loadHtml("vote",false,["ROLE"=>args_get("role")]);
        return true;
    }

    public static function getCounter():bool
    {
        @mkdir("data");
        @touch("data/counter");
        $a = file_get_contents("data/counter");
        if (empty($a)){
            $a=1;
            file_put_contents("data/counter",$a);
        }
        echo $a;
        return true;
    }

    public static function addCounter(bool$out=true):bool
    {
        @mkdir("data");
        @touch("data/counter");
        $a = file_get_contents("data/counter");
        if (empty($a)){
            $a=1;
        }else{
            $a=((int)$a)+1;
        }
        file_put_contents("data/counter",$a);
        if($out)echo $a;
        return true;
    }

    public static function getBestImg():bool
    {
        $result = [];
        for ($i=0;$i<3;$i++){
            $a = json_decode(file_get_contents("data/g".($i+1).".vote"),true);
            $max = $a[0];
            $m = 1;
            if($a[1]>$max){
                $m=2;
                $max = $a[2];
            }
            if($a[2]>$max){
                $m=3;
//                $max = $a[3];
            }
            $result[$i] = ["id"=>$i,"url"=>linkProcess("{LINK_img}")."?tag=g".($i+1)."i".$m];
        }
        echo json_encode($result);
        return true;
    }

    public static function bestImg():bool
    {
        loadHtml("best");
        return true;
    }
}